#include <stdio.h>
#include "stm32f1xx_hal.h"
#include "bsp_usart.h"
#include "oled.h"
#include "esp8266.h"

uint32_t fac_us;
extern uint8_t g_state_flag;
extern uint16_t uart3RxLen;
void SystemClock_Config(void);
char a[] = "AT\r\n";
int main()
{   
  
    HAL_Init();
    SystemClock_Config();
    bsp_usart1_Init();
    bsp_usart3_Init();
    OLED_Init();
    led_init();
    //    HAL_UART_Transmit(&huartx, (uint8_t *)&a[0], 1, 0xffff);
    esp8266_init();

    // printf("AT\r\n");
    OLED_ShowString(10, 10, "LED :", OLED_8X16);
    OLED_Update(); // 必须调用这个才能实际显示
    /*显示初始字符串*/
    while (1)
    {
        //        HAL_GPIO_TogglePin(GPIOE, GPIO_PIN_5);
        //        HAL_Delay(500);
        Key_Scan();
        if (g_UARTy_dma_buf_t.g_state_flag)
        {
         
            g_UARTy_dma_buf_t.g_state_flag = 0;
            HAL_UART_Transmit(&huartx, (uint8_t *)&g_UARTy_dma_buf_t.uart3Rxbuf, g_UARTy_dma_buf_t.uart3RxLen, 1000);
            HAL_UART_Transmit(&huartx, (uint8_t *)"\r\n", 2, 1000); 

            g_UARTy_dma_buf_t.uart3RxLen = 0;
            memset(g_UARTy_dma_buf_t.uart3Rxbuf, 0, sizeof(g_UARTy_dma_buf_t.uart3Rxbuf));
        }
        OLED_ShowString(60, 10, HAL_GPIO_ReadPin(GPIOE, GPIO_PIN_5) ? "OFF" : "ON ", OLED_8X16);
        OLED_Update();
        HAL_Delay(100);

    }
}

void for_delay_us(uint32_t nus)
{
    uint32_t Delay = nus * 168 / 4;
    do
    {
        __NOP();
    } while (Delay--);
}
void SystemClock_Config(void)
{
    RCC_OscInitTypeDef RCC_OscInitStruct = {0};
    RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

    // 1. 配置振荡器
    RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
    RCC_OscInitStruct.HSEState = RCC_HSE_ON; // //开启外部晶振(8MHz)
    RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
    RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
    RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
    RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9; // 8MHz * 9 = 72MHz
    if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
    {
        Error_Handler();
    }

    // 2.配置时钟树
    RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
    RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; // 系统时钟源选择PLL
    RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;        // AHB时钟=72MHz
    RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;         // APB1时钟=36MHz
    RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;         // APB2时钟=72MHz
    if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
    {
        Error_Handler();
    }
}
